import React, { Component } from "react";
import {authType,InteractionType} from "./selectData";
import Grid from '../../../../components/display/grid';
import OmsSelect from '../../../../components/display/omsSelect';
import { Form, Input, Row, Col, Button, Tree , message } from 'antd';
import {roleSave,getProAndCity,stubGroupList,idsList,prefixFile,fileImport} from '../../../../fetch/fetchApi';
import StubModal from './stubModal';
import SevenModal from './sevenModal';
import UploadPage from './uploadPage'
const FormItem = Form.Item;
const createForm = Form.create;
const TreeNode = Tree.TreeNode;
// const {TextArea} = Input;

class DataAuthAdd extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refresh:0,
            params:{

            },
            Type:0,
            address:[],
            selectedRowKeys:[],
            addStubList:[],
            addStubListCopy:[],
            selectedStubRow:[],
            visible:false,
            visible7:false,
            visible4Up:false,
            fromModify:false,
            selectInfo:{},
            autoExpandParent: true,
            checkedKeys:[],
            fileList:[],
            inputVal:undefined,
        };
        this.columns=[
            {
                title: '故障代码',
                dataIndex: 'c_name',
                key: '0',
            },
            {   
                title: '所属类别',
                dataIndex:'c_type_name',
                key: '1',
            },
            {   
                title: '优先级',
                dataIndex:'c_prioritye_name',
                key: '2',
            },
            {
                title: '操作',
                key: '3',
                render: (text,record) => (
                    <span>
                        <a onClick={()=>{this.choose(text)}}>选择</a>
                    </span>
                )
            },
        ];
        this.columns2=[
            {
                title: '组织机构',
                dataIndex: 'name',
                key: '0',
            },
            {
                title: '操作',
                key: '3',
                width:120,
                render: (text,record,index) => (
                    <span>
                        <a onClick={()=>{this.deletSub(text,record,index)}}>删除</a>
                    </span>
                )
            },
        ];
        this.columns3=[
            {
                title: '组织机构代码',
                dataIndex: 'licenceNo',
                key: '0',
            },
            {
                title: '企业名称',
                dataIndex: 'companyName',
                key: '1',
            },
            {
                title: '操作',
                key: '3',
				width:120,
                render: (text,record,index) => (
                    <span>
                        <a onClick={()=>{this.deletSub(text,record,index)}}>删除</a>
                    </span>
                )
            },
        ]
    }

    

    onExpand = (expandedKeys) => {
        console.log('onExpand', expandedKeys);
        this.setState({
          expandedKeys,
          autoExpandParent: false,
        });
      }

      onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        this.setState({ 
            checkedKeys:checkedKeys,
         });
      }
    
      onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
      }

      renderTreeNodes = (data) => {
        return data.map((item) => {
          if (item.children) {
            return (
              <TreeNode title={item.title} key={item.key} dataRef={item}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            );
          }
          return <TreeNode {...item} />;
        });
      }

    componentDidMount(){
        getProAndCity().then(response=>{
            if(response&&response.data&&response.data.code==="200"){
                let outer=response.data.data.map((item,index)=>{
                    let inner=item.cityList.map(inner=>{
                        return {
                            title:inner.name,
                            key:inner.id,
                        }
                    });
                    return {
                        title:item.province.name,
                        key:item.province.id,
                        children:inner,
                    }
                })
                let outerList=[
                    {
                        title:"全部",
                        key:"**",
                        children:outer
                }
                ]
                this.setState({
                    address:outerList
                },()=>{this.setState({
                    checkedKeys:window.LayoutTab['tabParam'].role?Object.values(window.LayoutTab['tabParam'].role)[0]:[]
                },()=>{console.log(this.state)})})
            }
        });
        //-----------------------addStubList
        if(window.LayoutTab['tabParam'].role){
            this.setState({
                fromModify:true,
                dataType:window.LayoutTab['tabParam'].dataType,
                selectInfo:window.LayoutTab['tabParam'],
                Type:Object.keys(window.LayoutTab['tabParam'].role)[0]
            },()=>{
                if(this.state.fromModify&&this.state.Type==1){
                    stubGroupList({ids:window.LayoutTab['tabParam'].role[1].join(',')}).then(response=>{
                        if(response&&response.data&&response.data.code==="200"){
                            this.setState({
                                addStubList:response.data.data,
                                addStubListCopy:response.data.data
                            })
                        }
                    })
                }
                if(this.state.fromModify&&this.state.Type==7){
                    debugger;
                    let ids=Object.values(window.LayoutTab['tabParam'].role).join(',')
                    idsList({ids:ids}).then(response=>{
                        if(response&&response.data&&response.data.code==="200"){
                            this.setState({
                                addStubList:response.data.data
                            })
                        }
                    })
                }
            })
        }
    }



    

    handleSubmit =(e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                return;
            }

            if(this.state.fromModify){
                values.appkeyA=window.LayoutTab['tabParam'].appkeyA;
                values.appkeyB=window.LayoutTab['tabParam'].appkeyB;
            }else{
                values.appkeyB=window.LayoutTab['tabParam'].keyId;
            }
            //1
            if(this.state.Type==1||this.state.Type==7){
                debugger;
                if(this.state.addStubList.length===0){
                    message.error('请添加权限');
                    return
                }
                values.role={[values.role]:this.state.addStubList.map(k=>k.appkey||k.id)}
            }
            if(this.state.Type==0||this.state.Type==6){
                if(this.state.checkedKeys.length===0){
                    message.error('请添加权限');
                    return
                }
                if(this.state.checkedKeys.some(k=>k==="**")){
                    values.role={[values.role]:["*"]}
                }else{
                    var city=this.state.checkedKeys.filter(k=>k.slice(2,6)!=="0000")
                    values.role={[values.role]:city}
                }
            }
            // console.log(values);
            roleSave(values).then(response=>{
                if(response&&response.data&&response.data.code==="200"){
                    message.success('操作成功，请前往数据权限页面点击刷新查看');
                }
            })
        });
    };

    getAuthType=(val)=>{
        this.setState({
            Type:val
        })
        if(val==="7"||val==="1"){
            this.setState({
                addStubList:[]
            })
        }
    }

    getAddress=(e)=>{
        console.log(e);
        this.setState({
            address:e
        })
    }

    onPopupVisibleChange=()=>{

    }

    openModal=()=>{
        this.setState({
            visible:true,
        })
    }

    handleCancel=()=>{
        this.setState({
            visible:false,
            visible7:false,
            visible4Up:false,
            hasGetApi:true,
        })
    }

    deletSub=(a,s,index)=>{
        debugger;
        this.setState({
            addStubList:this.state.addStubList.filter((_, i) => i !== index),
            selectedRowKeys:this.state.selectedRowKeys.filter(k=>k!==a.id)
        },()=>{
            console.log(this.state.selectedRowKeys)
            this.setState({
                addStubListCopy:this.state.addStubList
            })
        })
    }

    addItem=(data,type)=>{
		let exits=this.state.addStubList.some(item=>item.id===data.id);
        if(type=='single'){
            if(exits){
				let name=data.name;
				message.error(`${name?name:''}  该数据已经存在`);
                return
            }else{
				message.success('添加成功');
            }

        }

        setTimeout(()=>{
            this.setState({
                addStubList:this.state.addStubList.concat(data)
            },()=>{
                this.setState({
                    addStubListCopy:this.state.addStubList
                });
            })
        },0)

    }

    openSeven=()=>{
        this.setState({
            visible7:true
        })
    }

    getFileList=(fileList)=>{
        let transFiles=fileList.map(k=>({id:k['id'],name:k['name']}))
        console.log('transFiles',transFiles);
		let exitsDataNames=[];
        transFiles.map(k=>{
			let exits=this.state.addStubList.some(item=>item.id===k.id);
			if(exits){
				let name=k.name;
				exitsDataNames.push(name);
			}else{
				this.addItem(k);
            }
        })
        if(exitsDataNames.length>0){
			message.error(`数据已经存在：${exitsDataNames.join(' , ')}`)
        }else{
			message.success('批量添加成功');
        }
    }

    SearchText=(e)=>{
        console.log(e.target.value);
        this.setState({
            inputVal:e.target.value
        })
    }

    SearchItem=()=>{
        debugger;
        if(!this.state.inputVal){
            this.setState({
                addStubList:this.state.addStubListCopy
            })
        }else{
            this.setState({
                addStubList:this.state.addStubListCopy.filter(k=>k['name'].includes(this.state.inputVal))
            })
        }
    }


    batchDelete=()=>{
        let a = new Set(this.state.addStubList);
        let b = new Set(this.state.selectedStubRow);
        let difference = new Set([...a].filter(x => !b.has(x)));
        console.log('difference',difference);
        let newList=Array.from(difference);
        console.log('difference',newList);
        this.setState({
            addStubList:newList,
            selectedRowKeys:[],
        })
    }
      

    render() {
        const {getFieldDecorator} = this.props.form;
        const {selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRow) => {
                this.setState({
                    selectedRowKeys,
                    selectedStubRow: selectedRow
                })
            },
        };
        const config = {
            rules: [
                {
                    required: true,
                    message: "该项为必填项"
                }
            ]
        };
        let ids=this.state.addStubList.map(k=>k.id);
        let exportQs=`${prefixFile}/export.do?serviceName=stubGroup&fileName=桩群查询&searchJson={"ids":"${ids.join(',')}"}`;
        return(
            <div>
                <form form={this.props.form}>
                    <Row gutter={4} style={{display:'flex'}}>
                        <Col xl={5}>
                            <FormItem
                            >
                                {getFieldDecorator('role',{...config,...{initialValue:this.state.selectInfo.role?Object.keys(this.state.selectInfo.role)[0].toString():"0"}})(
                                    <OmsSelect disabled={this.state.fromModify} data={authType} placeholder={'权限类型'} onChange={this.getAuthType} />
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={5}>
                            <FormItem
                            >
                                {getFieldDecorator('dataType',{...config,...{initialValue:this.state.dataType?this.state.dataType.toString():"0"}})(
                                    <OmsSelect disabled={this.state.fromModify} data={InteractionType} placeholder={'交互方式'}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={5}>
                            <FormItem
                            >
                                <Button style={{marginRight:4}} type="primary" htmlType="submit" onClick={this.handleSubmit}>{'保存'}</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                {this.state.Type==0&&<div>
                    <Tree
                    checkable
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                >
                    {this.renderTreeNodes(this.state.address)}
                </Tree>
                </div>}
                {this.state.Type==6&&<div>
                    <Tree
                    checkable
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                >
                    {this.renderTreeNodes(this.state.address)}
                </Tree>
                </div>}
                {this.state.Type==1&&<div>
                    <Row gutter={8}>
                        <Col xl={4}>
                            <Input onChange={this.SearchText}/>
                        </Col>
                        <Col xl={20}>
                            <Button onClick={this.SearchItem} style={{marginRight:8}}>查询</Button>
                            <Button onClick={this.openModal} style={{marginRight:8}}>添加</Button>
                            <Button style={{marginRight:8}} onClick={()=>{this.setState({visible4Up:true})}}>批量添加</Button>
                            <Button onClick={this.batchDelete} style={{marginRight:8}}>批量删除</Button>
                            <a href={exportQs}>
                            <Button style={{marginRight:8}}>导出</Button>
                            </a>
                        </Col>
                    </Row>
                    <Grid className={'sc-table'} rowSelection={rowSelection} style={{marginTop:10}} columns={this.columns2} noFirstFech={true} dataSource={this.state.addStubList} pagination={false}/>
                </div>}
                {this.state.Type==7&&<div>
                    <Row gutter={8}>
                        <Col>
                            <Button onClick={this.openSeven} style={{marginRight:8}}>添加</Button>
                            <Button onClick={this.batchDelete} style={{marginRight:8}}>批量删除</Button>
                        </Col>
                    </Row>
                    <Grid className={'sc-table'} rowSelection={rowSelection} style={{marginTop:10}} columns={this.columns3} noFirstFech={true} dataSource={this.state.addStubList} pagination={false}/>
                </div>}
                <StubModal visible={this.state.visible} handleCancel={this.handleCancel} hasGetApi={this.state.hasGetApi} alreadyGet={this.alreadyGet} addItem={(data)=>this.addItem(data,'single')}/>
                <SevenModal appkey={window.LayoutTab['tabParam'].keyId} visible={this.state.visible7} handleCancel={this.handleCancel} hasGetApi={this.state.hasGetApi} alreadyGet={this.alreadyGet} addItem={(data)=>this.addItem(data,'single')}/>
                <UploadPage getFileList={this.getFileList} visible={this.state.visible4Up} handleCancel={this.handleCancel}/>
                {/* <Grid columns={this.columns} params={this.state.params} fetchData={fcodeListApi} refresh={this.state.refresh}></Grid> */}
            </div>
        )
    }
}
DataAuthAdd = createForm()(DataAuthAdd);
export default DataAuthAdd;